﻿using Microsoft.Win32;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ToolGen
{
    public partial class Form1 : Form
    {
        private string conn = string.Empty;
        private string server = string.Empty;
        private string codeGen = string.Empty;
        private string folderSave = string.Empty;        
        private static MySqlConnection _connMySQL = null;
        private static SqlConnection _connSqlServer = null;
        private static string _path = "";
        private bool _isProtobuff = false;
        private GenCode _genCode;
        private int _serverType = 1; // 1: MySQL, 2: SqlServer
        public Form1()
        {
            InitializeComponent();

            conn = txtConn.Text;
            cbServer.SelectedIndex = 0;
            cbCodeGen.SelectedIndex = 0;
    
        }

        private void btTestConn_Click(object sender, EventArgs e)
        {
            try
            {
                conn = txtConn.Text;
                server = cbServer.SelectedItem.ToString().ToLower();
                string mess = "Connection OK!";
                switch (server)
                {
                    case "mysql":
                        _serverType = 1;
                        _connMySQL = new MySqlConnection(conn);
                        _connMySQL.Open();
                        if(_connMySQL.State != ConnectionState.Open)
                        {
                            mess = "Connection False!";
                            btGenCode.Enabled = false;
                        }
                        else
                        {
                            btGenCode.Enabled = true;
                        }
                        OpenMessageBox(mess);
                        _connMySQL.Close();
                        _connMySQL.Dispose();
                        break;
                    case "sqlserver":
                        _serverType = 2;
                        _connSqlServer = new SqlConnection(conn);
                        _connSqlServer.Open();
                        
                        if (_connSqlServer.State != ConnectionState.Open)
                        {
                            mess = "Connection False!";
                            btGenCode.Enabled = false;
                        }
                        else
                        {
                            btGenCode.Enabled = true;
                        }
                        OpenMessageBox(mess);
                        _connSqlServer.Close();
                        _connSqlServer.Dispose();
                        break;
                    default:
                        OpenMessageBox("You have chose server type!");
                        break;
                }
            }
            catch(Exception ex)
            {
                btGenCode.Enabled = false;
                OpenMessageBox(ex.Message);
            }
        }

        private void btGenCode_Click(object sender, EventArgs e)
        {
            var tableNames = new List<string>();
            string sql = string.Empty;
            string tblName = string.Empty;
            _genCode = new GenCode(_serverType, txtFolderSave.Text, _connSqlServer, _connMySQL, _isProtobuff);

            if(grvTable.SelectedRows.Count !=0)
            {
                foreach(DataGridViewRow row in grvTable.Rows)
                {
                    if(row.Selected)
                    {
                        if (row.Cells != null && row.Cells.Count > 0)
                        {
                            if (row.Cells[0] != null && row.Cells[0].Value != null)
                            {
                                tblName = row.Cells[0].Value.ToString();
                                sql = string.Format("entity {0} {0} {1}", tblName, cbCodeGen.SelectedItem.ToString());
                                string[] segments = ParseCommand(sql);
                                _genCode.Generate(segments);
                            }
                        }
                        //tableNames.Add(row.Cells[0].Value.ToString());
                    }
                }
            }
            else
            {
                foreach(DataGridViewRow row in grvTable.Rows)
                {
                    if (row.Cells != null && row.Cells.Count > 0)
                    {
                        if (row.Cells[0] != null && row.Cells[0].Value!=null)
                        {
                            tblName = row.Cells[0].Value.ToString();
                            sql = string.Format("entity {0} {0} {1}", tblName, cbCodeGen.SelectedItem.ToString());
                            string[] segments = ParseCommand(sql);
                            _genCode.Generate(segments);
                        }
                    }
                }
            }

            OpenMessageBox("Gen Code OK!!!!!!");
        }

        private void OpenMessageBox(string message)
        {
            MessageBox.Show(message, "Gen Code", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk);
        }

        private string[] ParseCommand(string cmd)
        {
            string[] segments = cmd.Split(new char[] { ' ' });
            return segments;
        }

        private void btConnect_Click(object sender, EventArgs e)
        {
            try
            {
                conn = txtConn.Text;
                server = cbServer.SelectedItem.ToString().ToLower();
                _isProtobuff = Convert.ToBoolean(cbxProtobuff.Checked);
                var _dataTable = new DataTable();
                string sqlAllTable = MySql.ReturnAllTable();

                if (btConnect.Text == "Connect")
                {
                    switch (server)
                    {
                        case "mysql":
                            _serverType = 1;
                            _connMySQL = new MySqlConnection(conn);
                            _connMySQL.Open();
                            if (_connMySQL.State != ConnectionState.Open)
                            {
                                btGenCode.Enabled = false;
                            }
                            else
                            {
                                if (chkView.Checked)
                                {
                                    sqlAllTable = MySql.ReturnAllView();
                                }
                                else
                                {
                                    sqlAllTable = MySql.ReturnAllTable(); //MySql.ReturnAllTable(_connMySQL.Database);
                                }
                                using (MySqlCommand mysqlCmd = new MySqlCommand(sqlAllTable, _connMySQL))
                                {
                                    mysqlCmd.ExecuteNonQuery();
                                    var _da = new MySqlDataAdapter(mysqlCmd);
                                    _da.Fill(_dataTable);
                                    grvTable.DataSource = _dataTable;

                                    //Add a CheckBox Column to the DataGridView at the first position.
                                    //DataGridViewCheckBoxColumn checkBoxColumn = new DataGridViewCheckBoxColumn();
                                    //checkBoxColumn.HeaderText = "";
                                    //checkBoxColumn.Width = 30;
                                    //checkBoxColumn.Name = "checkBoxColumn";
                                    //grvTable.Columns.Insert(0, checkBoxColumn);

                                }
                                btGenCode.Enabled = true;
                                btConnect.Text = "Disconnect";
                            }

                            break;
                        case "sqlserver":
                            _serverType = 2;
                            _connSqlServer = new SqlConnection(conn);
                            _connSqlServer.Open();

                            if (_connSqlServer.State != ConnectionState.Open)
                            {
                                btGenCode.Enabled = false;
                            }
                            else
                            {
                                if (chkView.Checked)
                                {
                                    sqlAllTable = SqlServer.ReturnAllView();
                                }
                                else
                                {
                                    sqlAllTable = SqlServer.ReturnAllTable(_connSqlServer.Database);
                                }
                                using(SqlCommand cmd = new SqlCommand(sqlAllTable, _connSqlServer))
                                {
                                    cmd.ExecuteNonQuery();
                                    var _da = new SqlDataAdapter(cmd);
                                    _da.Fill(_dataTable);
                                    grvTable.DataSource = _dataTable;
                                }
                                btGenCode.Enabled = true;
                                btConnect.Text = "Disconnect";
                            }

                            break;
                        default:
                            OpenMessageBox("You have chose server type!");
                            break;
                    }
                }
                else
                {
                    btConnect.Text = "Connect";
                    grvTable.DataSource = null;
                }
            }
            catch (Exception ex)
            {
                btGenCode.Enabled = false;
                OpenMessageBox(ex.Message);
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }
}
